<template>
    <div>
        <!-- 面包屑 -->
        <breadcrumb></breadcrumb>
        <!--卡片视图-->
        <el-card>
            <!-- 按钮 -->
            <el-row>
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
            </el-row>

            <el-table :data="rolesList" border stripe>
                <el-table-column label="明细" type="expand" width="60">
                    <template #default="scope">
                        <!-- 渲染一级权限 -->
                        <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id"
                            :class="{ bdbottom: true, bdtop: i1 == 0, vcenter: true }">
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <!-- 渲染二级权限 -->
                                <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                                    :class="{ bdtop: i2 != 0, vcenter: true }">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{
                                                item2.authName
                                        }}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!-- 渲染三级权限 -->
                                        <el-tag type="warning" closable v-for="item3 in item2.children" :key="item3.id"
                                            @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column label="序号" type="index" width="60"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色名称" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="showEditDialog(scope.row.id)" :icon="Edit">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" @click="removeRoleById(scope.row.id)" :icon="Delete">
                           删除
                        </el-button>
                        <el-button size="small" type="warning" @click="showRightDialog(scope.row)" :icon="Setting">
                            分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色的对话框 -->
        <el-dialog title="添加角色" v-model="addDialogVisible" width="50%" @close="addRoleClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm(addFormRef)">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色的对话框 -->
        <el-dialog title="编辑角色" v-model="editDialogVisible" width="50%" @close="editRoleClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRole(editFormRef)">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限的对话框 -->
        <el-dialog title="分配权限" v-model="rightDialogVisible" width="50%" @close="rightDialogClosed">
            <el-tree ref="treeRef" :data="rightsList" :props="treeProps" node-key="id" show-checkbox default-expand-all
                :default-checked-keys="defaultKeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
  
    
</template>

<script  setup >
import {Edit,Delete,Setting} from '@element-plus/icons-vue'
import { onMounted, reactive, ref, } from 'vue';
import { getRolesList, removeRightId, addRole, editRoles, getRolesInfo, getTreeData, setRoles, deleteRoles } from '@/apis/power'
const rolesList = ref([])
const getRolesData = () => {
    getRolesList().then(res => {
        rolesList.value = res.data
    })
}
onMounted(() => {
    getRolesData()
})

//根据id删除角色下的权限
const removeRightById = (role, rightId) => {
    // console.log(role, rightId);
    ElMessageBox.confirm(
        '确定要删除改权限吗',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            removeRightId(role.id, rightId).then((res) => {
                console.log(res);
                if (res.meta.status !== 200) {
                    ElMessage({
                        type: 'error',
                        message: '删除权限失败',
                    })
                }
                //不建议重新获取角色列表，会导致页面刷新
                role.children = res.data
                ElMessage({
                    type: 'success',
                    message: '删除权限成功',
                })
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}

//添加角色
const addForm = reactive({
    roleName: '',
    roleDesc: ''
})
const addFormRules = {
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
}
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addRole(addForm).then(res => {
                addDialogVisible.value = false
                ElMessage({ message: '添加角色成功', type: 'success' })
                getRolesData()
            })
        }
    })
}
//监听添加角色对话框的关闭事件
const addRoleClosed = () => {
    addFormRef.value.resetFields()
}

//编辑角色
const editForm = reactive({
    roleName: '',
    roleDesc: '',
    roleId: ''
})
const editFormRules = addFormRules
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editRoleClosed = () => {
    editFormRef.value.resetFields()
}
const showEditDialog = (id) => {
    getRolesInfo(id).then(res => {
        editForm.roleName = res.data.roleName
        editForm.roleDesc = res.data.roleDesc
        editForm.roleId = res.data.roleId
        editDialogVisible.value = true
    })
}
const editRole = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            editRoles(editForm.roleId, editForm.roleName, editForm.roleDesc).then(res => {
                editDialogVisible.value = false
                getRolesData()
                ElMessage({ message: '修改角色成功', type: 'success' })
            })
        }
    })
}

//分配权限的对话框
const rightDialogVisible = ref(false)
//监听分配权限对话框的关闭事件
const rightDialogClosed = () => {
    defaultKeys.value = []
}
const treeRef = ref(null)
const rightsList = ref([])
//默认选中的节点id值数组
const defaultKeys = ref([])
//树形组件的属性绑定对象
const treeProps = reactive({
    label: 'authName',
    children: 'children'
})
//当前要分配权限的角色id
const roleId = ref('')
const showRightDialog = async (role) => {
    //获取权限列表
    const result = await getTreeData()
    rightsList.value = result.data
    //获取角色下所有三级权限的id
    getLeafKeys(role)
    //存储当前要分配权限的角色id
    roleId.value = role.id
    rightDialogVisible.value = true
}
const getLeafKeys = (node) => {
    //判断是否为三级权限
    if (!node.children) {
        return defaultKeys.value.push(node.id)
    }
    //如果不是三级权限，则递归操作
    node.children.forEach(item => {
        getLeafKeys(item)
    })
}
const allotRights = async () => {
    const keys = treeRef.value.getCheckedKeys().concat(treeRef.value.getHalfCheckedKeys())
    const idStr = keys.join(',')
    const res = await setRoles(roleId.value, idStr)
    if (res.meta.status !== 200) {
        return ElMessage({
            type: 'error',
            message: '分配权限失败',
        })
    }
    rightDialogVisible.value = false
    getRolesData()
    ElMessage({
        type: 'success',
        message: '分配权限成功',
    })
}

//根据ID删除角色
const removeRoleById = (id) => {
    ElMessageBox.confirm(
        '确定要删除该角色吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await deleteRoles(id)
            if (res.meta.status !== 200) {
                ElMessage({
                    type: 'error',
                    message: '删除角色失败',
                })
            }
            getRolesData()
            ElMessage({
                type: 'success',
                message: '删除角色成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除！',
            })
        })
}
</script>

<style scoped lang="scss">
.el-tag {
    margin: 6px;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.bdtop {
    border-top: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>
